package com.beerq.view;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beerq.R;
import com.beerq.util.AppConfig;
import com.beerq.util.BasicHttp;
import com.beerq.util.Constants;
import com.beerq.util.StringUtil;
import com.beerq.view.friends.FriendsManager;
import com.beerq.view.friends.ImageLookingActivity;
import com.beerq.view.friends.PostInfoActivity;
import com.beerq.view.me.LoginActivity;
import com.beerq.view.pulltorefresh.library.PullToRefreshBase.Mode;
import com.beerq.view.pulltorefresh.library.PullToRefreshListView;
import com.beerq.view_manager.AddImageManager;
import com.bumptech.glide.Glide;


import com.lzy.imagepicker.bean.ImageItem;

import java.util.ArrayList;

import static com.alibaba.fastjson.JSON.parseObject;
import static com.beerq.R.id.img;


/**
 * A simple {@link Fragment} subclass.
 * 发啤气
 */
public class ThiridFragment extends Fragment {


    PullToRefreshListView mPtrListView;

    private static final int PAGE_SIZE = 30;
    private int pageIndex = 1;


    private Activity mActivity;

    private View mVTabLine;

    private EditText mEditComt;
    private ViewGroup mVpComt;

    private ViewGroup mVpSuggest;

    private boolean mIsMine = false;

    private int currentTabIndex = 0;

    private ViewGroup mVpComtContent;

    private boolean isGetData=true;

    public ThiridFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_thirid, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mActivity = getActivity();
        mVpSuggest = (ViewGroup) mActivity.findViewById(R.id.horizontalScrollView);

        mPtrListView = (PullToRefreshListView) mActivity.findViewById(R.id.pull_listView);

        mVTabLine = mActivity.findViewById(R.id.v_friend_tab_line);
        mEditComt = (EditText) mActivity.findViewById(R.id.edit_comt);
        mVpComt = (ViewGroup) mActivity.findViewById(R.id.lin_comt);

        mActivity.findViewById(R.id.img_post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(Constants.userInfo==null){
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(intent);
                    return;
                }

                Intent intent = new Intent(mActivity, PostInfoActivity.class);
                startActivity(intent);

            }
        });

        mActivity.findViewById(R.id.lin_suggest_all).setOnClickListener(mOnClickListener);
        mActivity.findViewById(R.id.lin_care_friend).setOnClickListener(mOnClickListener);
        mActivity.findViewById(R.id.lin_mine_friend).setOnClickListener(mOnClickListener);

        mActivity.getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                calTabLinePosition((ViewGroup) mActivity.findViewById(R.id.lin_suggest_all));
            }
        });
    }




    @Override
    public void onResume() {
        super.onResume();
        if(isGetData){
            getData();
        }else {
            isGetData=true;
        }

        //获取当前屏幕内容的高度
        mActivity.getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if(!isHidden()){
                    Rect rect = new Rect();
                    mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                    if (bottom != 0 && oldBottom != 0 && bottom - rect.bottom <= 0) {
                        mVpComt.setVisibility(View.GONE);
                    } else {
                        mVpComt.setVisibility(View.VISIBLE);
                        mEditComt.setFocusable(true);
                        mEditComt.setFocusableInTouchMode(true);
                        mEditComt.requestFocus();
                    }
                }

            }
        });

    }


    private void getData() {
        if (currentTabIndex == 0) {
            initSuggestFrient(123, 0);
            getFriendList(123, 123, 1);
        } else if (currentTabIndex == 1) {
            initSuggestFrient(Constants.userInfo.getAppUserId(), 1);
            getFriendList(Constants.userInfo.getAppUserId(), Constants.userInfo.getAppUserId(), 2);
        } else {
            getFriendList(Constants.userInfo.getAppUserId(), Constants.userInfo.getAppUserId(), 0);
        }
    }


    private void getFriendList(int vipId, int userId, int sightType) {
        FriendsManager.getFriendContentById(mActivity, vipId, userId, pageIndex, PAGE_SIZE, sightType, new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(String resonseData) {
                JSONArray jsonArray = parseObject(resonseData).getJSONArray("Result");
                mPtrListView.setAdapter(new FriendsListAdapter(jsonArray));
            }

            @Override
            public void onFailure(String resonseData) {

            }
        });
    }


    private void initSuggestFrient(int vipid, int typee) {

        FriendsManager.getSuggestFriend(mActivity, vipid, typee, new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(String resonseData) {
                ViewGroup vP = (ViewGroup) mActivity.findViewById(R.id.lin_suggest_friend);
                vP.removeAllViews();
                JSONArray jsonArray = parseObject(resonseData).getJSONArray("Result");
//
                for (int i = 0, m = jsonArray.size(); i < m; i++) {
                    JSONObject temp = jsonArray.getJSONObject(i);
                    View view = mActivity.getLayoutInflater().inflate(R.layout.item_suggest_friends, null);
                    Glide.with(mActivity).load(temp.getString("HeadPic")).error(R.drawable.logo_error).into((ImageView) view.findViewById(R.id.img_user_logo));

                    String userName=temp.getString("UserName");

                    if(!StringUtil.isEmpty(userName) && userName.length()==11){
                        userName=userName.substring(0,3)+"****"+userName.substring(7,11);
                    }

                    ((TextView) view.findViewById(R.id.txt_user_name)).setText(userName);
                    view.setTag(temp.getIntValue("VipId"));

                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getFriendList((int) v.getTag(), 123, 0);
                        }
                    });

                    vP.addView(view);
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
                    params.setMargins(50, 0, 0, 0);
                }
            }

            @Override
            public void onFailure(String resonseData) {

            }
        });
    }


    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (v.getId() != R.id.lin_suggest_all) {
                if (Constants.userInfo == null) {
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(intent);
                    return;
                }
            }


            calTabLinePosition((ViewGroup) v);

            if (v.getId() == R.id.lin_mine_friend) {
                if (currentTabIndex == 2) {
                    return;
                }
                currentTabIndex = 2;
                mVpSuggest.setVisibility(View.GONE);
                mIsMine = true;

            } else {
                if (v.getId() == R.id.lin_care_friend) {
                    if (currentTabIndex == 1) {
                        return;
                    }
                    currentTabIndex = 1;
                } else {
                    if (currentTabIndex == 0) {
                        return;
                    }
                    currentTabIndex = 0;
                }
                mIsMine = false;
                mVpSuggest.setVisibility(View.VISIBLE);
            }
            getData();
        }
    };

    private void calTabLinePosition(ViewGroup vp) {

        LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mVTabLine.getLayoutParams();
        View son = (View) vp.getChildAt(0);
        lp.leftMargin = (int) (vp.getX() + son.getX());
        lp.width = son.getWidth();
        mVTabLine.setLayoutParams(lp);



    }

    public void showSoftInput(final Context context, final ViewGroup vpComt, final int vipid, final int replyId, final int sightid,final String reply) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        vpComt.setVisibility(View.VISIBLE);

        if(StringUtil.isEmpty(reply)){
            mEditComt.setHint("评论");
        }else {
            mEditComt.setHint("回复 "+reply+":");
        }


        vpComt.findViewById(R.id.btn_send_comt).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    if (mEditComt.getText().toString().length() == 0) {
                        return true;
                    }

                    FriendsManager.postComt(context, vipid, replyId, mEditComt.getText().toString(), sightid, new BasicHttp.IMyCallBack() {
                        @Override
                        public void onResponse(String resonseData) {

                            vpComt.setVisibility(View.GONE);
                            Toast.makeText(mActivity, "评论成功", Toast.LENGTH_SHORT).show();

                            TextView textView = new TextView(mActivity);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                            lp.setMargins(0, 10, 0, 0);
                            textView.setTextSize(14);


                            textView.setText(Constants.userInfo.getUserName() + ": " + mEditComt.getText());


                            mVpComtContent.addView(textView, mVpComtContent.getChildCount());
                            mVpComtContent.requestLayout();
                            mEditComt.setText("");
                        }

                        @Override
                        public void onFailure(String resonseData) {

                        }
                    });


                    return true;
                }
                return false;
            }
        });

//        vpComt.findViewById(R.id.btn_send_comt).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                if(mEditComt.getText().toString().length()==0){
//                    return;
//                }
//
//                FriendsManager.postComt(context, vipid, replyId, mEditComt.getText().toString(), sightid, new BasicHttp.IMyCallBack() {
//                    @Override
//                    public void onResponse(String resonseData) {
//                        mEditComt.setText("");
//                        vpComt.setVisibility(View.GONE);
//                    }
//
//                    @Override
//                    public void onFailure(String resonseData) {
//
//                    }
//                });
//
//            }
//        });


        //imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }


    public class FriendsListAdapter extends BaseAdapter {
        private JSONArray mItems;

        SparseArray<String> imgArrays=new SparseArray<>();

        public FriendsListAdapter(JSONArray jsonArray) {
            mItems = jsonArray;
        }

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public JSONObject getItem(int position) {
            return mItems.getJSONObject(position - 1);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(mActivity);
                convertView = inflater.inflate(R.layout.list_item_friends, null);
                holder = new ViewHolder();
                holder.imgUserLogo = (ImageView) convertView.findViewById(R.id.img_user_logo);
                holder.txtUserName = (TextView) convertView.findViewById(R.id.txt_user_name);
                holder.chCare = (CheckBox) convertView.findViewById(R.id.ch_care);
                holder.txtContent = (TextView) convertView.findViewById(R.id.txt_content);
                holder.imgLike = (ImageView) convertView.findViewById(R.id.img_like);
                holder.imgMessage = (ImageView) convertView.findViewById(R.id.img_message);
                holder.img = (ImageView) convertView.findViewById(img);
                holder.txtPostTime = (TextView) convertView.findViewById(R.id.txt_time);
                holder.txtLikeCount = (TextView) convertView.findViewById(R.id.txt_like_count);
                holder.holdView = convertView;
                holder.txtDelete = (TextView) convertView.findViewById(R.id.txt_delete);
                holder.fl_commit = (LinearLayout) convertView.findViewById(R.id.commit);
                ;
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final JSONObject jsonObject = mItems.getJSONObject(position);

            final int sightId = jsonObject.getIntValue("SightId");


            String userName=jsonObject.getString("UserName");

            if(!StringUtil.isEmpty(userName) && userName.length()==11){
                userName=userName.substring(0,3)+"****"+userName.substring(7,11);
            }


            holder.txtUserName.setText(userName);

            holder.imgMessage.setTag(holder.fl_commit);

            holder.imgMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mVpComt.setVisibility(View.VISIBLE);
                    mVpComtContent = (ViewGroup) v.getTag();

                    if (Constants.userInfo == null) {
                        Intent intent = new Intent(mActivity, LoginActivity.class);
                        mActivity.startActivity(intent);
                        return;
                    }
                    showSoftInput(mActivity, mVpComt, Constants.userInfo.getAppUserId(), 0, sightId,"");
                }
            });


            if (mIsMine) {
                holder.chCare.setVisibility(View.GONE);
                holder.txtDelete.setVisibility(View.VISIBLE);
                holder.txtDelete.setTag(sightId);
                holder.txtDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FriendsManager.deleteContent(mActivity, Constants.userInfo.getAppUserId(), (int) holder.txtDelete.getTag(), new BasicHttp.IMyCallBack() {
                            @Override
                            public void onResponse(String resonseData) {
                                ((BaseActivity) mActivity).showToast("删除成功");
                                getFriendList(Constants.userInfo.getAppUserId(), Constants.userInfo.getAppUserId(), 0);
                            }

                            @Override
                            public void onFailure(String resonseData) {

                            }
                        });
                    }
                });
            } else {
                holder.txtDelete.setVisibility(View.GONE);
                if (Constants.userInfo == null || jsonObject.getIntValue("VipId") == Constants.userInfo.getAppUserId()) {//如果是自己看自己的话 影藏掉关注功能
                    holder.chCare.setVisibility(View.GONE);
                } else {
                    holder.chCare.setVisibility(View.VISIBLE);
                    if (jsonObject.getBoolean("IsSubscribe")) {
                        holder.chCare.setChecked(true);
                        holder.chCare.setText("已关注");

                    } else {
                        holder.chCare.setChecked(false);
                        holder.chCare.setText("未关注");
                    }

                    holder.chCare.setTag(jsonObject.getIntValue("VipId"));
                    holder.chCare.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            FriendsManager.focusFriends(mActivity, Constants.userInfo.getAppUserId(), (int) v.getTag(), ((CheckBox) v).isChecked() ? 0 : 1, new BasicHttp.IMyCallBack() {
                                @Override
                                public void onResponse(String resonseData) {

                                }
                                @Override
                                public void onFailure(String resonseData) {

                                }
                            });
                        }
                    });
                }
            }


            LinearLayout.LayoutParams lp1=(LinearLayout.LayoutParams)holder.img.getLayoutParams();
            lp1.height=AppConfig.devicePixelsWidth;
            holder.img.setLayoutParams(lp1);
            String path=jsonObject.getString("Pics");

            imgArrays.put(holder.img.hashCode(),path);

            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent=new Intent(mActivity,ImageLookingActivity.class);

                    isGetData=false;

                    ImageItem imageItem=new ImageItem();
                    imageItem.path=imgArrays.get(v.hashCode());

                    ArrayList<ImageItem> imageItems=new ArrayList<ImageItem>();
                    imageItems.add(imageItem);

                    AddImageManager.mListImgs=imageItems;

                    intent.putExtra("canNotDelete",true);
                    intent.putExtra(ImageLookingActivity.EXTRA_IMAGE_INDEX,0);
                    mActivity.startActivity(intent);
                }
            });


            Glide.with(mActivity).load(path).into(holder.img);
            Glide.with(mActivity).load(jsonObject.getString("HeadPic")).into(holder.imgUserLogo);
            holder.txtContent.setText(jsonObject.getString("Desc"));
            holder.txtPostTime.setText(jsonObject.getString("CreateTime"));
            holder.txtLikeCount.setText(jsonObject.getIntValue("UpVoteCount") + "次赞");
            holder.txtLikeCount.setTag(jsonObject.getIntValue("UpVoteCount"));


            JSONArray jsonArray = jsonObject.getJSONArray("SightCommentInfo");

            if (jsonArray != null) {
                holder.fl_commit.removeAllViews();
                for (int i = 0, l = jsonArray.size(); i < l; i++) {
                    final JSONObject temp = jsonArray.getJSONObject(i);
                    TextView textView = new TextView(mActivity);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    lp.setMargins(0, 10, 0, 0);
                    textView.setTextSize(14);
                    textView.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.selector_comt));


                    String commentBody=temp.getString("CommentBody");
                    if(commentBody.indexOf("回复")>-1){
                        commentBody=commentBody.split("回复")[0];
                    }

                    textView.setTag(temp.getIntValue("VipId") + "," + sightId+","+commentBody);
                    textView.setTag(R.id.horizontal, holder.fl_commit);

                    if(Constants.userInfo!=null){
                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mVpComt.setVisibility(View.VISIBLE);
                                mVpComtContent = (ViewGroup) v.getTag(R.id.horizontal);
                                String[] arr = v.getTag().toString().split(",");
                                showSoftInput(mActivity, mVpComt, Integer.parseInt(arr[0]), Constants.userInfo.getAppUserId(), Integer.parseInt(arr[1]),arr[2]);
                            }
                        });
                    }else {
                        textView.setEnabled(false);
                    }

                    textView.setText(temp.getString("CommentBody") + " " + temp.getString("CommentContent"));
                    holder.fl_commit.addView(textView, lp);
                }
            }


            holder.imgLike.setTag(null);
            holder.imgLike.setTag(holder.imgLike.getId(), holder.txtLikeCount);

            ((View) holder.imgLike.getParent()).setTag(sightId);

            if(jsonObject.getBoolean("IsLike")){
                holder.imgLike.setTag(1);
                holder.imgLike.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.care));
            }else{
                holder.imgLike.setTag(null);
                holder.imgLike.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.no_care));
            }


            holder.imgLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
//                    v.setEnabled(false);

                    if(Constants.userInfo==null){
                        goTologin();
                        return;
                    }
                    final ImageView fv = (ImageView) v;

                    int voteType = 0;
                    if (fv.getTag() != null) {
                        voteType = 1;
                    }
                    FriendsManager.like(mActivity, Constants.userInfo.getAppUserId(), (int) ((View) v.getParent()).getTag(), voteType, new BasicHttp.IMyCallBack() {
                        @Override
                        public void onResponse(String resonseData) {


                            TextView txtCount = (TextView) fv.getTag(fv.getId());

                            if (fv.getTag() == null) {
                                fv.setTag(1);
                                txtCount.setTag(((int) txtCount.getTag() + 1));
                                txtCount.setText((int) txtCount.getTag() + "次赞");
                                fv.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.care));
                            } else {
                                fv.setTag(null);
                                int count = (int) txtCount.getTag();
                                fv.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.no_care));
                                if (count < 0) {
                                    txtCount.setText("0次赞");
                                    return;
                                }
                                txtCount.setTag(((int) txtCount.getTag() - 1));
                                txtCount.setText((int) txtCount.getTag() + "次赞");
                            }
                        }

                        @Override
                        public void onFailure(String resonseData) {
                        }
                    });
                }
            });
            return convertView;
        }

        public void setItems(JSONArray list) {
            mItems = list;
            if (mItems == null) {
                mItems = new JSONArray();
            }
            if (mItems.size() >= PAGE_SIZE) {
                mPtrListView.setMode(Mode.BOTH);
            } else {
                mPtrListView.setMode(Mode.PULL_FROM_START);
            }
            notifyDataSetChanged();
            mPtrListView.getRefreshableView().setSelected(true);
            mPtrListView.getRefreshableView().setSelection(0);
        }
//        public void attachItems(List<JSONObject> list) {
//            if (mItems == null) {
//                mItems = new ArrayList<JSONObject>();
//            }
//
//            if( list==null || list.size()==0){
//                mPtrListView.setMode(Mode.PULL_FROM_START);
//            }
//
//
//            if (list != null) {
//                mItems.addAll(list);
//                if (list.size() >= PAGE_SIZE) {
//                    mPtrListView.setMode(Mode.BOTH);
//                } else {
//                    mPtrListView.setMode(Mode.PULL_FROM_START);
//                }
//                notifyDataSetChanged();
//            }
//
//        }
    }

    private void goTologin(){
        Intent intent = new Intent(mActivity, LoginActivity.class);
        mActivity.startActivity(intent);
    }

    public class ViewHolder {
        public ImageView imgUserLogo;
        public TextView txtUserName;
        public CheckBox chCare;
        public ImageView img;
        public TextView txtContent;
        public ImageView imgLike;
        public ImageView imgMessage;
        public TextView txtPostTime;
        public TextView txtDelete;
        public TextView txtLikeCount;
        public View holdView;
        public LinearLayout fl_commit;
    }

}
